﻿var canvas = document.getElementById('map-pic');
//var canvasmn = document.getElementById('minimap');
var canvasfake = document.getElementById('map-pic-fake');
if (canvas != null) {
    //set width height device

    var devicewidth = $('#container').width();
    var deviceheight = $('#container').height();

    ////////////////////////////////
    var $device = $('#device');
    var $mapcontain = $('#map-container');
    var $map = $('#map-pic');
    var $lbody = $('body');
    var $body = $('#body');
    var $header = $('#header');
    var $butdir = $('.butdir');
    var $butsside = $('#but_ssidebar');
    var $buthside = $('#but_hsidebar');
    var $savemap = $('#savemap');
    var $closesavemap = $('#closesavemap');
    var $tabcontent = $('#tabs-content');
    var $findaround = $('.findplacearound');
    var $infoform = $('#info_place_form');
    var $bordercontent = $('.border-content');
    var bordercontentVis = '.border-content.visible';
    var $aroundplaceM = $('#placearoundform_content');
    var $layout = $('#layout-wrapper');
    var slider = '.slider-content';
    var $placepage = $('#placepage');
    var $mainpage = $('#mainpage');
    var $resli = $('.list_res li');
    var $placearoundform = $('#placearoundform_replace');
    var $listplace = $('.listplace');
    var $notfound = $('#notfound');
    var $placetype = $('#lst_placetype');
    var $range = $('#num_range');
    var $leftbox = $('#leftbox');
    var $sidebar = $('#sidebar');
    var $ruler = $('#ruler');
    var $bar_mile = $('#bar_mile');
    var $info_replace = $('#info_replace');
    var $bar_mid = $('#bar_mid');
    var $bar_km = $('#bar_km');
    var $text_mile = $('#text_mile');
    var $text_km = $('#text_km');
    var $indicatezoom = $('#indicatezoom');
    var $item0 = $('#contextmenu_map .mn_item0');
    var $item1 = $('#contextmenu_map .mn_item1');
    var $item2 = $('#contextmenu_map .mn_item2');
    var $item3 = $('#contextmenu_map .mn_item3');
    var $item4 = $('#contextmenu_map .mn_item4');
    var $item5 = $('#contextmenu_map .mn_item5');
    var $startpoint = $('.setstartpoint');
    var $endpoint = $('.setendpoint');
    var $butzoom = $('.butzoom');
    var $navs = $('#navs');
    var nav = $('.nav');
    var mainnav = 'main-nav';
    var $yourlocation = $('#yourlocation');
    var $mapmn = $('#minimap-wrap');
    var $maptype = $('#maptype');
    var $viewmap = $('.viewmap');
    var $contextmenu = $('#contextmenu_map');
    var paint = canvas.getContext('2d');
    //var paintmn = canvasmn.getContext('2d');
    var paintfake = canvasfake.getContext('2d');
    var timeZoomFx = 0;
    var timeZoomCount = 0;
    var cellwidth = 256;
    var cellheight = 256;
    var rows = 0;
    var cols = 0;
    var pathsimg = "";
    var pathmimg = "";
    var extension = "";
    var Mapx = 0;
    var Mapy = 0;
    var curMapx = 0;
    var syncGNP = false;
    var curMapy = 0;
    var velx = 0;
    var vely = 0;
    var svelx = 0;
    var svely = 0;
    var timedr = 0;
    var minter = 0;
    var interDir = 0;
    var mapcurTop = 0;
    var interDr = 0;
    var mapcurLeft = 0;
    var width = 0;
    var height = 0;
    var deviceW = 0;
    var deviceH = 0;
    var rateScreenx = 0;
    var rateScreeny = 0;
    var fmapwidth = cellwidth * cols;
    var fmapheight = cellheight * rows;
    var rmapwidth = 0;
    var rmapheight = 0;
    var centerx = 0;
    var centery = 0;
    var centerLat = 0;
    var centerLong = 0;
    var rateLat = 0;
    var rateLong = 0;
    var sidewidth = $sidebar.width();
    var maxlevelz = 5;
    var curlevelz = 1;
    var nPicx = 0;
    var nPicy = 0;
    var m_pzx = 0;
    var m_pzy = 0;
    var startLat = 0;
    var startLong = 0;
    var endLat = 0;
    var endLong = 0;
    var markLat = 0;
    var markLong = 0;
    var levelz = 1;
    var linedr = false;
    var maptype = true;
    var stopCpos = false;
    var mapDrag = false;
    var navDrag = false;
    var curIndexP = -1;
    var zoomfx = false;
    var capZoomfx = false;
    var Clear = false;
    var navInit = false;
    var img_arrs = new Array();
    //var img_arrs_fake = new Array();
    var img_arrs_mn = new Array();
    var arrow_arrs = new Array();
    var point_arrs = new Array();
    var mpoint_arrs = new Array();
    var poinmark_arrs = new Array();
    var marker_arrs = new Array();
    var stylefill = 'rgba(50,255,0,1)';
    var stylebd = 'rgba(0,0,0,0.5)';
    var stylestroke = 'rgba(180,0,255,0.5)';
    var triStyle = 'rgba(100,255,0,1)';
    var devices = ['iphonevertical', 'iphonehorizoltal', 'ipadvertical', 'ipadhorizoltal'];
    var iDvs = 0;
    $(window).resize(function () {
        resizewindow(true);
    });
    function resizewindow(getdata) {
        var bodyh = $(window).height() - $header.height() - 2;
        if (bodyh < 400) bodyh = 400;
        //$body.css('height', bodyh);
        deviceH = $layout.height();
        deviceW = $layout.width();
        $map.height($mapcontain.height());
        $map.width($mapcontain.width());
        $tabcontent.css('maxHeight', bodyh - (135 + 20));
        $bordercontent.css('maxHeight', bodyh - (135 + 20));
        $aroundplaceM.css('maxHeight', bodyh - (230 + 20));
        $listplace.css('maxHeight', bodyh - (135 + 20));
        $tabcontent.css('height', bodyh - (135 + 20));
        $bordercontent.css('height', bodyh - (135 + 20));
        $listplace.css('height', bodyh - (135 + 20));
        $aroundplaceM.css('height', bodyh - (230 + 20));
        canvas.width = $mapcontain.width();
        canvas.height = $mapcontain.height();
        canvasfake.width = $mapcontain.width();
        canvasfake.height = $mapcontain.height();
        //canvasmn.width = $mapmn.width() - 4;
        //canvasmn.height = $mapmn.height() - 22;
        width = canvas.width;
        height = canvas.height;
        rateScreenx = width >= height ? 1 : width / height;
        rateScreeny = height >= width ? 1 : height / width;

        if (!navInit) {
            for (var i = 0; i < nav.length; i++) {
                var navw = 0;
                for (var j = 0; j < $(nav[i]).find('li').length; j++) {
                    navw += $($(nav[i]).find('li')[j]).width();
                }
                $(nav[i]).width(navw);
            }
            navInit = true;
        }

        if (slideNav != null) slideNav.Clear();
        FixPosNav();
        UpdateWindow(getdata);
    }
    var slidertop = 0;
    function ResetSlider(el,rate) {
        //var el = $('.page');
        //for (var i = 0; i < el.length; i++) {
            var cel = $(el).find('.slider-content');
            $(el).find('.m_bdcontent').unbind()
            .mousedown(function () { sliderOb.Clear(); })
            .bind('dragstart', function (e) {
                if (!EventForSlider(this)) return;
                sliderOb.Init(); mapcurTop = e.offsetY;
                slidertop = GetNumber($(this).find('.list_res').css('margin-top')); 
            })
            .bind('drag', function (e) {
                if (!EventForSlider(this)) return;
                sliderOb.Update(e.offsetY - mapcurTop);
                var reVal = FixSlider(this, slidertop + e.offsetY - mapcurTop);
                $(this).find('.list_res').css('margin-top', reVal);
                $(el).find('.slider-content span').css('top',-reVal * rate);
            })
            .bind('dragend', function () {
                if (!EventForSlider(this)) return;
                sliderOb.Finish(this,rate); 
            });
        //}
    }

    var navleft = 0;
    var slideNav = new Slidedownslow();
    var sliderOb = new SliderEasing();

    $navs.mousedown(function () { slideNav.Clear(); })
    .bind('dragstart', function (e) { if (!EventForNav()) return; slideNav.Init(); navDrag = true; mapcurLeft = e.offsetX; navleft = GetNumber($navs.find('.nav.show').css('left')); })
    .bind('drag', function (e) { if (!EventForNav()) return; slideNav.Update(e.offsetX - mapcurLeft); $navs.find('.nav.show').css('left', FixNavLeft(navleft + e.offsetX - mapcurLeft)); })
    .bind('dragend', function () { if (!EventForNav()) return; slideNav.Finish(); });

    function EventForSlider(el) {
        if ($(el).find('.list_res').height() > $(el).height()) return true;
        return false;
    }
    function EventForNav() {
        if ($navs.find('.nav.show').width() > deviceW) return true;
        return false;
    }

    function FixNavLeft(val) {
        var navwidth = $navs.find('.nav.show').width();
        if (val > 0) {
            return 0;
        } else if (val + navwidth < deviceW) {
            return deviceW - navwidth;
        }

        return val;
    }

    function FixSlider(el,val) {
        if (val > 0) return 0;
        var $con = $(el).find('.list_res');
        if ($con.height() + val < $(el).height()) {
            return $(el).height() - $con.height();
        }

        return val;
    }

    function SliderEasing() {
        var navinter = 0;
        var velocityX = 0;
        var svelocityX = 0;

        this.Init = function () {
            velocityX = svelocityX = 0;
            var tvelx = 0;
            var timecom = 0;
            clearInterval(navinter);
            navinter = setInterval(function () {
                velocityX -= 0.2 * velocityX;
                if (tvelx != velocityX) {
                    tvelx = velocityX;
                    timecom = 0;
                } else {
                    timecom++;
                }
                if (timecom > 15) { velocityX = 0; }
            }, 10);
        }

        this.Update = function (valx) {
            velocityX += valx - svelocityX;
            svelocityX = valx;
        }

        this.Clear = function () { clearInterval(navinter); }

        this.Finish = function (el, rate) {
            clearInterval(navinter);
            var scale = false;
            var scaleval = 0;
            navinter = setInterval(function () {
                //_utimeVarAni++;

                //var dx = parseInt(_uAvarAni * Math.sin(_utimeVarAni / _timedivideVar));

                //var val = dx * velocityX;
                //_uAvarAni -= _Avardelta;
                //if ($(el).find('.slider-content span').css('display') == 'none') clearInterval(navinter);
                var val = 0.1 * velocityX;
                var top = GetNumber($(el).find('.list_res').css('margin-top')) + val;
                var reVal = FixSlider(el, top);
                $(el).find('.list_res').css('margin-top', reVal);
                $(el).find('.slider-content span').css('top', -reVal * rate);
                if (!scale) {
                    var fixval = FixSlider(el, top);
                    if (fixval != top) {
                        scaleval = fixval;
                        scale = true;
                    }
                } else {
                    //velocityX -= Math.abs(GetNumber($navs.find('.nav.show').css('left')) - fixval) * 0.5;
                }

                velocityX -= val * 0.3;
                if (Math.abs(velocityX) < 1) clearInterval(navinter);
            }, 10);
        }
    }

    function Slidedownslow() {
        var navinter = 0;
        var velocityX = 0;
        var svelocityX = 0;

        this.Init = function () {
            velocityX = svelocityX = 0;
            var tvelx = 0;
            var timecom = 0;
            clearInterval(navinter);
            navinter = setInterval(function () {
                velocityX -= 0.2 * velocityX;
                if (tvelx != velocityX) {
                    tvelx = velocityX;
                    timecom = 0;
                } else {
                    timecom++;
                }
                if (timecom > 15) { velocityX = 0;}
            }, 10);
        }

        this.Update = function (valx) {
            velocityX += valx - svelocityX;
            svelocityX = valx;
        }

        this.Clear = function () { clearInterval(navinter); }

        this.Finish = function () {
            clearInterval(navinter);
            var scale = false;
            var scaleval = 0;
            navinter = setInterval(function () {
                //_utimeVarAni++;

                //var dx = parseInt(_uAvarAni * Math.sin(_utimeVarAni / _timedivideVar));

                //var val = dx * velocityX;
                //_uAvarAni -= _Avardelta;

                var val = 0.1 * velocityX;
                var left = GetNumber($navs.find('.nav.show').css('left')) + val;
                $navs.find('.nav.show').css('left', FixNavLeft(left));
                if (!scale) {
                    var fixval = FixNavLeft(left);
                    if (fixval != left) {
                        scaleval = fixval;
                        scale = true;
                    }
                } else {
                    //velocityX -= Math.abs(GetNumber($navs.find('.nav.show').css('left')) - fixval) * 0.5;
                }

                velocityX -= val * 0.4;
                //if (Math.abs(velocityX) < 1) clearInterval(navinter);
            }, 10);
        }
    }

    function FixPosNav() {
        for (var i = 0; i < nav.length; i++) {
            var width = $(nav[i]).width();
            var left = 0;
            if (width < deviceW) left = parseInt((deviceW - width) / 2);
            $(nav[i]).css('left', left);
        }
    }
    function PointMark(lat, long, x, y, info) {
        this.x = x;
        this.y = y;
        this.visible = true;
        this.lat = lat;
        this.long = long;
        this.info = info;
        this.Init = function (lat, long, info) {
            this.lat = lat;
            this.long = long;
            this.info = info;
            var pos = ConvertToMapP(this.lat, this.long);
            this.x = pos[0];
            this.y = pos[1];
            this.visible = true;
        }
        this.Draw = function () {
            if (this.visible) {
                paint.beginPath();
                paint.arc(curMapx + this.x, curMapy + this.y, 4, 0, 2 * Math.PI, false);
                paint.fillStyle = stylefill;
                paint.fill();
                paint.lineWidth = 1;
                paint.strokeStyle = stylebd;
                paint.stroke();
            }
        }
        this.GetX = function () {
            return this.x + curMapx;
        }
        this.GetY = function () {
            return this.y + curMapy;
        }
        this.focus = function (mx, my) {
            if (mx >= this.x + curMapx - 4 && mx <= this.x + curMapx + 4 && my >= this.y + curMapy - 4 && my <= this.y + curMapy + 4) return true;
            return false;
        }
    }
    function UpdateWindow(getdata) {
        fmapwidth = cellwidth * cols;
        fmapheight = cellheight * rows;
        nPicx = parseInt(width / cellwidth + 2);
        nPicy = parseInt(height / cellheight + 2);
        nPicx = nPicx > cols ? cols : nPicx;
        nPicy = nPicy > rows ? rows : nPicy;
        rmapwidth = fmapwidth - width;
        rmapheight = fmapheight - height;

        var id = '#' + $(bdcontent + '.visible').find(slidecontent).attr('id');
        $(id).unbind();
        var rateH = ResizeSlider(id);
        BindSlider(id, rateH);

        if (pathmimg != "" && getdata) { GetDataImg(true); }
    }
    function ClearArrPoint() {
        var length = point_arrs.length;
        for (var i = 0; i < length; i++) {
            point_arrs.pop();
            mpoint_arrs.pop();
            poinmark_arrs.pop();
        }
    }
    function AdjustmentRateBar() {
        switch (curlevelz) {
            case 1:
                $bar_mid.animate({ width: 102 }, 'normal');
                $bar_mile.animate({ left: 75 }, 'normal');
                $bar_km.animate({ left: 100 }, 'normal');
                $text_km.text("2 km");
                $text_mile.text("1 mile");
                break;
            case 2:
            case 3:
                $bar_mid.animate({ width: 102 }, 'normal');
                $bar_mile.animate({ left: 56 }, 'normal');
                $bar_km.animate({ left: 100 }, 'normal');
                if (curlevelz == 2) {
                    $text_km.text("1 km");
                    $text_mile.text("2000 ft");
                } else {
                    $text_km.text("500 m");
                    $text_mile.text("1000 ft");
                }
                break;
            case 4:
                $bar_mid.animate({ width: 82 }, 'normal');
                $bar_mile.animate({ left: 56 }, 'normal');
                $bar_km.animate({ left: 80 }, 'normal');
                $text_km.text("200 m");
                $text_mile.text("500 ft");
                break;
            case 5:
                $bar_mid.animate({ width: 82 }, 'normal');
                $bar_mile.animate({ left: 44 }, 'normal');
                $bar_km.animate({ left: 80 }, 'normal');
                $text_km.text("100 m");
                $text_mile.text("200 ft");
                break;
        }
    }
    function ClearPoint() {
        ClearPointa();
        ClearPointb();
        ClearPointn();
    }
    function ClearPointn() {
        markLat = markLong = 0;
        Marker.lat = Marker.long = 0;
        Marker.visible = false;
    }
    function ClearPointa() {
        startLat = startLong = 0;
        Markera.lat = Markera.long = 0;
        Markera.visible = false;
        $('#startPoint').find('input[type="text"]').val("Nhập vị trí bắt đầu");
    }
    function SetPointa(info) {
        if (startLat == endLat && startLong == endLong) ClearPointb();
        ClearArrPoint();
        ClearPointn();
        MoveMapToPosition(Markera.x, Markera.y, 10, true);
        FindDir();
        ViewStreetForm(false, info);
    }
    function SetPointb(info) {
        if (endLat == startLat && endLong == startLong) ClearPointa();
        ClearArrPoint();
        ClearPointn();
        MoveMapToPosition(Markerb.x, Markerb.y, 10, true);
        FindDir();
        ViewStreetForm(true, info);
    }
    function SetPointn() {
        ClearPointb();
        ClearPointa();
        ClearArrPoint();
        MoveMapToPosition(Marker.x, Marker.y, 10, true);
        var inter = setInterval(function () {
            if (curMapx == Mapx && curMapy == Mapy) {
                Marker.visible = true;
                ShowInfoForm(Marker.GetX() + 15, Marker.GetY() + 15);
                getInfofromMarker(markLat, markLong);
                clearInterval(inter);
            }
        }, 100);
        //ViewStreetForm(true, info);
    }
    function ClearPointb() {
        endLat = endLong = 0;
        Markerb.lat = Markerb.long = 0;
        Markerb.visible = false;
        $('#endPoint').find('input[type="text"]').val("Nhập vị trí kết thúc");
    }
    function Top(el) {
        return GetNumber(el.css('top'));
    }
    function Left(el) {
        return GetNumber(el.css('left'));
    }
    function GetNumber(input) {
        return Number(input.substr(0, input.length - 2));
    }
    function ishideInfoForm() {
        if ($infoform.css('display') != 'none' && $infoform.css('opacity') == 1) return true;
        return false;
    }
    function HideInfoForm() {
        if (ishideInfoForm()) {
            $infoform.css('display', 'none');
            //$infoform.fadeOut('fast');
        }
    }
    function ShowInfoForm(x, y) {
        if (!mapDrag) {
            $infoform.css({ left: x - 140, top: y - 190 });
            $infoform.fadeIn('fast');
        }
    }
    canvas.addEventListener("click", function (evt) {
        var mx = evt.offsetX; var my = evt.offsetY;
        if (Marker.visible && mx > Marker.GetX() && mx < Marker.GetX() + Marker.GetWidth() && my > Marker.GetY() && my < Marker.GetY() + Marker.GetHeight()) {
            ShowInfoForm(Marker.GetX() + 15, Marker.GetY() + 15);
            getInfofromMarker(markLat, markLong);
        } else if (Markera.visible && mx > Markera.GetX() && mx < Markera.GetX() + Markera.GetWidth() && my > Markera.GetY() && my < Markera.GetY() + Markera.GetHeight()) {
            ShowInfoForm(Markera.GetX() + 15, Markera.GetY() + 15);
            getInfofromMarker(startLat, startLong);
        } if (Markerb.visible && mx > Markerb.GetX() && mx < Markerb.GetX() + Markerb.GetWidth() && my > Markerb.GetY() && my < Markerb.GetY() + Markerb.GetHeight()) {
            ShowInfoForm(Markerb.GetX() + 15, Markerb.GetY() + 15);
            getInfofromMarker(endLat, endLong);
        }
    }, false);
    canvas.addEventListener("mousemove", function (evt) {
        var mx = evt.offsetX; var my = evt.offsetY;
        for (var i = 0; i < poinmark_arrs.length; i++) {
            if (poinmark_arrs[i].focus(mx, my)) {
                ShowInfoForm(poinmark_arrs[i].GetX() - 15, poinmark_arrs[i].GetY() - 15);
                getInfofromMarker(poinmark_arrs[i].lat, poinmark_arrs[i].long);
                break;
            }
        }
    }, false);
    function getInfofromMarker(lat, long) {
        $.ajax({ url: "/Home/GetInfoFromCoordinate?zoom=" + curlevelz + "&plat=" + lat + "&plong=" + long,
            type: 'POST', cache: false, dataType: 'text',
            contentType: "text/html; charset=utf-8", data: null, beforeSend: function () { },
            success: function (data) {
                $info_replace.html(data);
            }, error: function () { }
        });
    }
    function Marker(link) {
        this.x = 0;
        this.y = 0;
        this.imgob = new Image();
        this.imgob.src = link;
        this.visible = false;
        this.el = null;
        this.lat = 0;
        this.long = 0;
        this.info = "";
        this.Init = function (type, el) {
            this.el = el;
            switch (type) {
                case -1:
                    markLat = parseFloat(el.attr('datalat'));
                    markLong = parseFloat(el.attr('datalong'));
                    break;
                case 0:
                    startLat = parseFloat(el.attr('datalat'));
                    startLong = parseFloat(el.attr('datalong'));
                    break;
                case 1:
                    endLat = parseFloat(el.attr('datalat'));
                    endLong = parseFloat(el.attr('datalong'));
                    break;
            }
            this.lat = parseFloat(el.attr('datalat'));
            this.long = parseFloat(el.attr('datalong'));
            this.info = ""; //el.parent().parent().find('.address').text();
            var pos = ConvertToMapP(this.lat, this.long);
            this.x = pos[0];
            this.y = pos[1];
            this.visible = true;
        }
        this.UpdatePos = function (x, y) {
            this.x = x;
            this.y = y;
            this.visible = true;
        }
        this.UpdateCoor = function (lat, long) {
            this.lat = lat;
            this.long = long;
        }
        this.Update = function (type) {
            this.Init(type, this.el);
        }
        this.GetWidth = function () {
            return 25;
        }
        this.GetHeight = function () {
            return 45;
        }
        this.GetY = function () {
            return this.y + curMapy - 42;
        }
        this.GetX = function () {
            return this.x + curMapx - 18;
        }
        this.Draw = function () {
            if (this.visible) {
                try {
                    paint.drawImage(this.imgob, 0, 0, this.imgob.width, this.imgob.height,
                    this.x + curMapx - 18, this.y + curMapy - 42, this.imgob.width, this.imgob.height);
                } catch (ex) { }
            }
        }
    }
    function MapCell(link, name, deltapx, deltapy) {
        this.row = Number(name.split('_')[0]);
        this.col = Number((name.split('_')[1]));
        this.posx = this.col * cellwidth - deltapx; //deltapx > 0 ? deltapx - this.col * cellwidth : this.col * cellwidth;
        this.posy = this.row * cellheight - deltapy; //deltapy > 0 ? deltapy - this.row * cellheight : this.row * cellheight;
        this.link = link;
        this.imgob = new Image();
        this.imgob.src = link;

        this.Draw = function () {
            try {
                paint.drawImage(this.imgob, 0, 0, this.imgob.width, this.imgob.height, this.posx + curMapx, this.posy + curMapy, cellwidth, cellheight);
            } catch (ex) { }
        };
        this.DrawM = function () {
            try {
                //paintmn.drawImage(this.imgob, 0, 0, this.imgob.width, this.imgob.height, this.posx + curMapx, this.posy + curMapy, cellwidth, cellheight);
            } catch (ex) { }
        };
        this.DrawF = function () {
            try {
                paintfake.drawImage(this.imgob, 0, 0, this.imgob.width, this.imgob.height, this.posx + curMapx, this.posy + curMapy, cellwidth, cellheight);
            } catch (ex) { }
        };
    };
    function SearchPlace(el) {
        var str = $(el).val();
        $.ajax({ url: "/Mobile/Search?keywords=" + str,
            type: 'POST', cache: false, dataType: 'text',
            contentType: "text/html; charset=utf-8", data: null, beforeSend: function () { },
            success: function (data) {
                $('#placepage .list_res').html(data);
                if (resizeElView('placepage')) {
                    $('#placepage').find(slider).fadeIn('fast');
                }
            }, error: function () { }
        });
        //$(el).selectAll();
    }

    function GetUri() {
        $.ajax({ url: "/Home/GetUri", type: 'GET', cache: false, dataType: 'Json',
            contentType: "text/html; charset=utf-8", data: null, beforeSend: function () { },
            success: function (data) {
                pathmimg = data[0]; pathsimg = data[1]; extension = data[2];
                centerx = data[3]; centery = data[4]; centerLat = data[5];
                centerLong = data[6]; rateLat = data[7]; rateLong = data[8];
                GetNumPic(true, true);
            }, error: function () { }
        });
    }
    function pad2(val) {
        var str = (parseInt(val) > 9 ? "" : "0") + parseInt(val).toString();
        return str;
    }
    function Distance(x1, y1, x2, y2) {
        return Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2));
    }
    function InitArrow() {
        /*if (endLat != 0 && startLat != 0) {
        var distance = 0;
        for (var i = 0; i < mpoint_arrs.length - 2; i += 2) {
        distance += Distance(mpoint_arrs[i], mpoint_arrs[i + 1], mpoint_arrs[i + 2], mpoint_arrs[i + 3]);
        }
        for (var i = 0; i < arrow_arrs.length; i++)
        arrow_arrs.pop();
        var n = parseInt(distance / 150) > 1 ? parseInt(distance / 150) : 1
        var delta = distance / n;
        for (var i = 0; i < n; i++) {
        arrow_arrs[i] = new arrow(i, delta);
        }
        }*/
    }

    function arrow(pos, delta) {
        var x1 = mpoint_arrs[0];
        var x2 = mpoint_arrs[2];
        var y1 = mpoint_arrs[1];
        var y2 = mpoint_arrs[3];
        var dirx = x2 - x1;
        var diry = y2 - y1;
        var ratex = Math.abs(dirx) > Math.abs(diry) ? dirx / Math.abs(dirx) : dirx / Math.abs(diry);
        var ratey = Math.abs(diry) > Math.abs(dirx) ? diry / Math.abs(diry) : diry / Math.abs(dirx);
        var px1, px2, px3, py1, py2, py3;

        Init(true);

        function Init(haspos) {
            if (haspos) {
                /*var valx = delta * pos * ratex;
                var valy = delta * pos * ratey;
                    
                px1 = x1 + valx; py1 = 13 + y1 + valy;
                px2 = x1 - 7 + valx; py2 = y1 + valy;
                px3 = x1 + 7 + valx; py3 = y1 + valy;*/
                px1 = x1; py1 = 13 + y1;
                px2 = x1 - 7; py2 = y1;
                px3 = x1 + 7; py3 = y1;
            } else {
                px1 = x1; py1 = 13 + y1;
                px2 = x1 - 7; py2 = y1;
                px3 = x1 + 7; py3 = y1;
            }
        }

        this.Update = function () {
            if (px1 >= x2) {
                Init(false);
            }
            px1 += ratex; px2 += ratex; px3 += ratex; py1 += ratey; py2 += ratey; py3 += ratey;
        }
        this.Draw = function () {
            paint.beginPath();
            paint.moveTo(px1, py1);
            paint.lineTo(px2, py2);
            paint.lineTo(px3, py3);
            paint.closePath();
            paint.fillStyle = stylestroke;
            paint.fill();
        }
    }
    function DrDir() {
        if (endLat == 0 || startLat == 0) return;
        for (var i = 0; i < arrow_arrs.length; i++) {
            arrow_arrs[i].Update();
            arrow_arrs[i].Draw();
        }
    }
    function GetZoom(zx, zy) {
        if (syncGNP) return;
        InitZoomFx();
        HideInfoForm();
        var inter = setInterval(function () {
            if (timeZoomFx >= 25) {
                var data = { "array": [curlevelz, levelz, curMapx, curMapy, zx, zy, width, height] };
                $.ajax({ url: "/Home/Zoom",
                    type: 'POST', cache: false, dataType: 'Json',
                    contentType: "application/json; charset=utf-8", data: JSON.stringify(data), beforeSend: function () { },
                    success: function (result) {
                        curlevelz = levelz;
                        curMapx = Mapx = result[0];
                        curMapy = Mapy = result[1];
                        centerx = result[2]; centery = result[3]; centerLat = result[4];
                        centerLong = result[5]; rateLat = result[6]; rateLong = result[7];
                        AdjustmentRateBar();
                        GetNumPic(true, false);
                        ConvertPoints();
                        if (Markerb.lat != 0) {
                            var pos = ConvertToMapP(Markerb.lat, Markerb.long);
                            Markerb.UpdatePos(pos[0], pos[1]);
                        }
                        if (Markera.lat != 0) {
                            var pos = ConvertToMapP(Markera.lat, Markera.long);
                            Markera.UpdatePos(pos[0], pos[1]);
                        }
                        if (Marker.lat != 0) {
                            var pos = ConvertToMapP(Marker.lat, Marker.long);
                            Marker.UpdatePos(pos[0], pos[1]);
                        }

                        syncGNP = false;
                    }, error: function () { levelz = curlevelz; }
                });
                clearInterval(inter);
            }
        }, 10);
    }
    function GetNumPic(getdata, resize) {
        $.ajax({ url: "/Home/GetNumPic?zoom=" + curlevelz,
            type: 'GET', cache: false, dataType: 'Json',
            contentType: "text/html; charset=utf-8", data: null, beforeSend: function () { },
            success: function (result) {
                cols = result[0];
                rows = result[1];
                if (resize) resizewindow(getdata);
                else UpdateWindow(getdata);
            }, error: function () { }
        });
    }
    /*function GetDataImg() {
    $.ajax({ url: "/Home/GetData?zoom=" + curlevelz + "&x=" + curMapx + "&y=" + curMapy + "&width=" + width + "&height=" + height,
    type: 'POST', cache: false, dataType: 'Json',
    contentType: "text/html; charset=utf-8", data: null, beforeSend: function () { },
    success: function (result) {
    InitImg(result[0], result[1], result[2]);
    }, error: function () { }
    });
    }*/
    function ConvertPoints() {
        var cplength = mpoint_arrs.length;

        var pmlength = poinmark_arrs.length;
        var index = 0;
        for (var i = 0; i < pmlength; i++) poinmark_arrs.pop();

        for (var i = 0; i < cplength; i++) mpoint_arrs.pop();
        for (var i = 0; i < point_arrs.length; i += 2) {
            var pos = ConvertToMapP(point_arrs[i], point_arrs[i + 1]);
            mpoint_arrs[i] = pos[0];
            mpoint_arrs[i + 1] = pos[1];
            poinmark_arrs[index++] = new PointMark(point_arrs[i], point_arrs[i + 1], pos[0], pos[1], "");
        }
    }
    function SetPoint(lat, long) {
        ClearPoint();
        var plength = point_arrs.length;
        for (var i = 0; i < plength; i++) point_arrs.pop();

        markLat = lat;
        markLong = long;
        point_arrs[0] = lat;
        point_arrs[1] = long;
        ConvertPoints();
        Marker.UpdateCoor(lat, long);
        Marker.UpdatePos(mpoint_arrs[0], mpoint_arrs[1]);
        MoveMapToPosition(mpoint_arrs[0], mpoint_arrs[1], 10, true);
    }
    function InitPointwithArr(data) {
        ClearArrPoint();
        /*point_arrs[0] = startLat;
        point_arrs[1] = startLat;*/
        point_arrs[0] = startLat;
        point_arrs[1] = startLong;
        var i = 2;
        for (i; i < data.length + 2; i++) {
            point_arrs[i] = data[i - 2];
        }
        point_arrs[point_arrs.length] = endLat;
        point_arrs[point_arrs.length] = endLong;

        ConvertPoints();
    }
    function InitPoint(isStart) {
        ClearArrPoint();
        var time = 0;
        endLat = endLong = startLat = startLong = 0;
        Marker.visible = false; Markera.visible = false; Markerb.visible = false;
        var lstlength = point_arrs.length;
        for (var i = 0; i < lstlength; i++) point_arrs.pop();
        var inter = setInterval(function () {
            var lstlatlong = $(bordercontentVis + ' ul li span');
            for (var i = 0; i < lstlatlong.length; i++) {
                point_arrs[i * 2] = parseFloat($(lstlatlong[i]).attr('datalat'));
                point_arrs[i * 2 + 1] = parseFloat($(lstlatlong[i]).attr('datalong'));
            }
            if (time++ >= 30 || lstlatlong.length > 0) {
                if (point_arrs.length > 0) {
                    ConvertPoints();
                    if (isStart) MoveMapToPosition(mpoint_arrs[0], mpoint_arrs[1], 10, true);
                }
                else {
                    //if (isStart) ShowNotFound();
                }
                clearInterval(inter);
            }
        }, 100);
    }

    function GetDataImg(changeType) {
        var scol = parseInt((curMapx < 0 ? -curMapx : 0) / cellwidth);
        var srow = parseInt((curMapy < 0 ? -curMapy : 0) / cellheight);
        var arrname = new Array();
        var index = 0;
        for (var i = srow; i < nPicy + srow && i < rows; i++) {
            for (var j = scol; j < nPicx + scol && j < cols; j++) {
                arrname[index++] = pad2(i) + "_" + pad2(j);
            }
        }
        if (!changeType && img_arrs.length < arrname.length) changeType = true;
        InitImg(arrname, changeType, scol, srow);
        //GetImgMn(changeType, scol, srow);
    }
    function DrawMn() {
        var interDrMn = setInterval(function () {
            if (img_arrs_mn.length > 0) {
                //if (Clear) paintmn.clearRect(0, 0, canvasmn.width, canvasmn.height);
                for (var i = 0; i < img_arrs_mn.length; i++) {
                    img_arrs_mn[i].DrawM();
                }
            }
        }, 50);
    }
    function FixMapPosition() {
        var done = false;

        if (curMapx > sidewidth) { curMapx = sidewidth; done = true; }
        else if (curMapx < -rmapwidth) { curMapx = -rmapwidth; done = true; }

        if (curMapy > 0) { curMapy = 0; done = true; }
        else if (curMapy < -rmapheight) { curMapy = -rmapheight; done = true; }

        return done;
    }
    function ZoomFX() {
        if (timeZoomFx <= 40 && levelz != curlevelz) {
            var delta = -7 + 0.1 * Math.pow(2, curlevelz - 1); ;
            if (curlevelz < levelz) delta = 15 + 0.3 * Math.pow(2, curlevelz - 1);
            timeZoomCount = timeZoomFx * delta;
            paint.clearRect(0, 0, canvas.width, canvas.height);
        }
        var totalx = timeZoomCount * rateScreenx;
        var totaly = timeZoomCount * rateScreeny;
        var left = totalx * m_pzx / width;
        var top = totaly * m_pzy / height;

        paint.drawImage(canvasfake, 0, 0, width, height, -left, -top,
            width + totalx, height + totaly);

        if (timeZoomFx++ >= 100) {
            zoomfx = false;
            Clear = true;
            timeZoomFx = 0;
        }
    }
    function InitZoomFx() {
        for (var i = 0; i < img_arrs.length; i++)
            img_arrs[i].DrawF();
        var imgcount = img_arrs.length;
        for (var i = 0; i < imgcount; i++)
            img_arrs.pop();
        /*Markera.visible = false;
        Markerb.visible = false;*/
        zoomfx = true;
        timeZoomCount = timeZoomFx = 0;
        stopCpos = true;
    }

    function DrawMap() {
        clearInterval(interDr);
        interDr = setInterval(function () {
            if (Clear) paint.clearRect(0, 0, canvas.width, canvas.height);
            if (zoomfx) ZoomFX();

            if (img_arrs.length > 0) {
                for (var i = 0; i < img_arrs.length; i++) {
                    img_arrs[i].Draw();
                }
                if (endLat != 0 && startLat != 0) {
                    for (var i = 0; i < mpoint_arrs.length - 2; i += 2) {
                        paint.beginPath();
                        paint.strokeStyle = stylestroke;
                        paint.lineCap = 'round';
                        paint.lineWidth = 5;
                        paint.moveTo(curMapx + mpoint_arrs[i], curMapy + mpoint_arrs[i + 1]);
                        paint.lineTo(curMapx + mpoint_arrs[i + 2], curMapy + mpoint_arrs[i + 3]);
                        paint.stroke();
                    }
                } else {
                    for (var i = 0; i < mpoint_arrs.length; i += 2) {
                        if ((startLat != point_arrs[i] && startLong != point_arrs[i + 1]) &&
                            (endLat != point_arrs[i] && endLong != point_arrs[i + 1]) &&
                            (markLat != point_arrs[i] && markLong != point_arrs[i + 1])) {
                            /*paint.beginPath();
                            paint.arc(curMapx + mpoint_arrs[i], curMapy + mpoint_arrs[i + 1], 4, 0, 2 * Math.PI, false);
                            paint.fillStyle = stylefill;
                            paint.fill();
                            paint.lineWidth = 1;
                            paint.strokeStyle = stylebd;
                            paint.stroke();*/
                            poinmark_arrs[parseInt(i / 2)].Draw();
                        }
                    }
                }
                //if (endLat == 0 || startLat == 0) return;
                for (var i = 0; i < arrow_arrs.length; i++) {
                    arrow_arrs[i].Update();
                    arrow_arrs[i].Draw();
                }

                if (levelz == curlevelz) {
                    Marker.Draw(); Markera.Draw(); Markerb.Draw();
                }
            }
        }, 10);
        DrawMn();
    }
    function InitImg(arrayName, changeType, scol, srow) {
        if (changeType) {
            var imgcount = img_arrs.length;
            for (var i = 0; i < imgcount; i++) img_arrs.pop();
        }

        for (var i = 0; i < arrayName.length; i++) {
            var name = arrayName[i];
            var link = (maptype ? pathmimg : pathsimg) + levelz + "_" + name + extension;

            if (changeType) {
                img_arrs[i] = new MapCell(link, name, 0, 0);
            } else {
                if (!Exist(link)) {
                    for (var j = 0; j < img_arrs.length; j++) {
                        if (img_arrs[j].col < scol || img_arrs[j].col > scol + nPicx - 1
                                || img_arrs[j].row < srow || img_arrs[j].row > srow + nPicy - 1) {
                            try {
                                img_arrs[j] = new MapCell(link, name, 0, 0);
                            } catch (ex) { }
                            break;
                        }
                    }
                }
            }
        }
    }
    function GetImgMn(changeType, scol, srow) {
        var elleft = width - GetNumber($mapmn.css('right')) - $mapmn.width();
        var eltop = GetNumber($mapmn.css('top'));
        var npx = parseInt((elleft - sidewidth) / cellwidth);
        var index = 0;
        var path = (maptype ? pathsimg : pathmimg) + levelz + "_";
        //if (!changeType && img_arrs_mn.length < 6) changeType = true;
        for (var i = srow; i < srow + 2; i++) {
            for (var j = scol + npx; j < scol + npx + 3 && j < cols; j++) {
                var name = pad2(i) + "_" + pad2(j);
                var link = path + name + extension;
                if (changeType) {
                    img_arrs_mn[index++] = new MapCell(link, name, elleft, eltop);
                } else {
                    if (!ExistMn(link)) {
                        for (var x = 0; x < img_arrs_mn.length; x++) {
                            if (img_arrs_mn[x].col < scol + npx || img_arrs_mn[x].col > scol + npx + 3
                                || img_arrs_mn[x].row < srow || img_arrs_mn[x].row > srow + 1) {
                                img_arrs_mn[x] = new MapCell(link, name, elleft, eltop);
                                break;
                            }
                        }
                    }
                }
            }
        }
    }
    function ExistMn(link) {
        for (var i = 0; i < img_arrs_mn.length; i++)
            if (img_arrs_mn[i].link == link) return true;
        return false;
    }
    function Exist(link) {
        for (var i = 0; i < img_arrs.length; i++)
            if (img_arrs[i].link == link) return true;
        return false;
    }
    $closesavemap.live('click', function () { $lbody.find('#wrap_cap').replaceWith(''); });
    function ShowSideBar() {
        if ($butsside.css('display') != 'none') {
            $butsside.fadeOut('fast', function () {
                $sidebar.animate({ left: 0 }, 'normal', function () {
                    $leftbox.fadeIn('fast');
                });
                $ruler.animate({ left: 380 }, 'normal');
            });
            sidewidth = $sidebar.width();
        }
    }
    $maptype.click(function () { maptype = !maptype; if(maptype)$(this).removeClass('map').addClass('sat'); else $(this).removeClass('sat').addClass('map'); triStyle = maptype ? 'rgba(100,255,0,1)' : 'rgba(255,100,0,1)'; stylestroke = maptype ? 'rgba(180,0,255,0.5)' : 'rgba(0,255,0,0.5)'; GetDataImg(true); maptype ? $ruler.removeClass('white').addClass('black') : $ruler.removeClass('black').addClass('white'); });
    $buthside.click(function () {
        $sidebar.animate({ left: -350 }, 'normal', function () {
            $butsside.fadeIn('fast');
        });
        $ruler.animate({ left: 30 }, 'normal');
        $leftbox.fadeOut('fast');
        if (curMapx > 0) {
            ChangeMapPosition(-curMapx, 0, 25, false);
        }
        sidewidth = 0;
    });
    $butsside.click(function () {
        ShowSideBar();
    });
    $map.bind('mousedown', function () {
        stopCpos = true;
        velx = 0; vely = 0;
        timedr = 0;
        FixMapPosition();
        HideInfoForm();
    }).bind('mouseup', function () {
        mapDrag = false;
    })
        .bind('dragstart', function (e) {
            mapDrag = true;
            Clear = true;
            mapcurTop = e.offsetY;
            mapcurLeft = e.offsetX;
            var tvelx = 0;
            var tvely = 0;
            var timecom = 0;
            minter = setInterval(function () {
                timedr++;
                velx -= 0.2 * velx;
                vely -= 0.2 * vely;
                if (tvelx != velx || tvely != vely) {
                    tvelx = velx;
                    tvely = vely;
                    timecom = 0;
                } else {
                    timecom++;
                }
                if (timecom > 15) { velx = 0; vely = 0; }
            }, 10);
        })
        .bind('drag', function (e) {
            curMapx = e.offsetX - mapcurLeft + Mapx;
            curMapy = e.offsetY - mapcurTop + Mapy;
            velx += e.offsetX - svelx; vely += e.offsetY - svely;
            svelx = e.offsetX; svely = e.offsetY;
            FixMapPosition();
            GetDataImg(false);
        }).bind('dragend', function (e) {
            clearInterval(minter);
            Mapx = curMapx;
            Mapy = curMapy;
            Clear = false;
            ChangeMapPosition(velx, vely, 0, true);
        });
    function MoveMapToPosition(x, y, duration, fixpos) {
        var zx = x != 'none' ? (-(x - width / 2) - Mapx) : 0;
        var zy = y != 'none' ? (-(y - height / 2) - Mapy) : 0;
        ChangeMapPosition(zx, zy, duration, fixpos);
    }
    function ChangeMapPosition(deltax, deltay, duration, fixpos) {
        var dirx, diry, ldirx, ldiry, time;

        if (duration > 0) {
            dirx = deltax / duration;
            diry = deltay / duration;
            time = duration;
            //ldirx = deltax - dirx * duration;
            //ldiry = deltay - diry * duration;
            //time = duration + 1;
        } else {
            ldirx = deltax;
            ldiry = deltay;
        }

        stopCpos = false;
        Clear = true;
        var changePosinter = setInterval(function () {
            if (duration < 1) {
                dirx = ldirx * 0.1;
                diry = ldiry * 0.1;
                ldirx -= dirx * 0.5;
                ldiry -= diry * 0.5;
            }

            curMapx += dirx;
            curMapy += diry;

            /*if (time - 1 == 0 && duration > 0) {
            curMapx += ldirx;
            curMapy += ldiry;
            } else {
            curMapx += dirx;
            curMapy += diry;
            }*/

            if (fixpos) stop = FixMapPosition();
            GetDataImg(false);
            if ((--time == 0 && duration > 0) || stopCpos || (duration < 1 && Math.abs(dirx) < 1 && Math.abs(diry) < 1)) {
                Mapx = curMapx;
                Mapy = curMapy;
                Clear = false;
                clearInterval(changePosinter);
            }
        }, 10);
    }
    function XenZd(level) {
        if (level != levelz) {
            if (level > levelz) levelz++;
            else levelz--;

            m_pzx = width / 2;
            m_pzy = height / 2;

            GetZoom(m_pzx, m_pzy);
            if (110 - levelz * 22 > 50) $indicatezoom.css('z-index', 11);
            else $indicatezoom.css('z-index', 12);
        }
    }
    function XenZ(zoomin, x, y) {
        /*var delta = 0.02;
        var size = 1;
        if (!zoomin) delta = -delta;

        var inter = setInterval(function () {
        var val = delta * 0.4;
        paint.scale(size += val, size);
        paint.translate(-0.1 * width, -0.1 * height);
        delta -= val;
        if (delta <= 0.000000001) {
        clearInterval(inter);
        }
        }, 10);*/
        var done = false;
        if (zoomin && levelz < maxlevelz) { levelz++; done = true; }
        else if (!zoomin && levelz > 1) { levelz--; done = true; }

        if (done) {
            GetZoom(x, y);
            $indicatezoom.stop().animate({ top: 111 - (levelz - 1) * 22 }, 'fast');
            if (110 - levelz * 22 > 50) $indicatezoom.css('z-index', 11);
            else $indicatezoom.css('z-index', 12);
        }
    }
    function ConvertToMapP(lat, long) {
        var distancelat = centerLat - lat;
        var distancelong = long - centerLong;

        var tempratex = (distancelong / rateLong);
        var tempratey = (distancelat / rateLat);
        //tempratex -= tempratex * 0.01;
        //tempratey -= tempratey * 0.12;
        tempratey -= tempratey * 0.102;

        var deltay = parseInt(tempratey * 18 * Math.pow(2, curlevelz - 1));
        var deltax = parseInt(tempratex * 30 * Math.pow(2, curlevelz - 1));

        var pos = new Array();

        pos[0] = deltax + centerx;
        pos[1] = deltay + centery;

        return pos;
    }
    function FindDir() {
        if (startLat != 0 && endLat != 0) {
            var length = mpoint_arrs.length;
            for (var i = 0; i < length; i++) mpoint_arrs.pop();
            $.ajax({ url: "/Home/FindDuong?sLat=" + startLat + "&sLong=" + startLong + "&eLat=" + endLat + "&eLong=" + endLong,
                type: 'POST', cache: false, dataType: 'Json',
                contentType: "text/html; charset=utf-8", data: null, beforeSend: function () { },
                success: function (data) {
                    InitPointwithArr(data);
                    InitArrow();
                }, error: function () { }
            });
        }
    }
    function ToLocation(lat, long) {
        var pos = ConvertToMapP(lat, long);
        for (var i = 0; i < mpoint_arrs.length; i += 2) {
            if (parseInt(mpoint_arrs[i]) == parseInt(pos[0]) && parseInt(mpoint_arrs[i + 1]) == parseInt(pos[1])) {
                curIndexP = i;
                UpdatePosIndicateFlag();
                break;
            }
        }
        MoveMapToPosition(pos[0], pos[1], 10, true);
    }
    $butzoom.click(function () {
        var idel = $(this).attr('id');
        m_pzx = width / 2;
        m_pzy = height / 2;
        if (idel == "pluszoom") {
            XenZ(true, m_pzx, m_pzy);
        } else {
            XenZ(false, m_pzx, m_pzy);
        }
    });
    var elY = 0; var eY = 0; var zoomdrag = false;
    $indicatezoom.bind('dragstart', function (e) {
        elY = GetNumber($indicatezoom.css('top'));
        eY = e.offsetY; zoomdrag = true;
    }).bind('drag', function (e) {
        var topval = elY + e.offsetY - eY;
        if (topval < 22) topval = 22;
        else if (topval > 111) topval = 111;
        $(this).css('top', topval);
        if (topval > 88) XenZd(1);
        else if (topval > 66) XenZd(2);
        else if (topval > 44) XenZd(3);
        else if (topval > 22) XenZd(4);
        else XenZd(5);
    }).bind('dragend', function (e) {
        zoomdrag = false;
    });
    function HideNotFound() {
        $notfound.css('display', 'none');
    }
    function ShowNotFound() {
        $notfound.css('display', 'block');
    }
    $placetype.change(FindAround);
    $range.change(FindAround);
    function FindAround() {
        if (Marker.lat == 0) return;
        var type = parseInt($placetype.val());
        var range = parseInt($range.val());

        $.ajax({ url: "/Home/GetPlaceAroundLongLat?plat=" + Marker.lat + "&plong=" + Marker.long + "&type=" + type + "&r=" + range,
            type: 'POST', cache: false, dataType: 'text',
            contentType: "text/html; charset=utf-8", data: null, beforeSend: function () { HideNotFound(); },
            success: function (data) {
                $placearoundform.html(data);
                FinishSearchAround();
                ClearArrPoint();
                if (data == "") {
                    ShowNotFound();
                } else {
                    InitPoint(false);
                    SetPointn();
                }
            }, error: function (httpReq, status, exception) {
            }
        });
    }
    $findaround.live('click', function () {
        HideSubList();
        var lat = parseFloat($(this).parent().attr('datalat'));
        var long = parseFloat($(this).parent().attr('datalong'));
        var type = parseInt($placetype.val());
        var range = parseInt($range.val());

        var $el = $(this);
        $.ajax({ url: "/Home/GetPlaceAroundLongLat?plat=" + lat + "&plong=" + long + "&type=" + type + "&r=" + range,
            type: 'POST', cache: false, dataType: 'text',
            contentType: "text/html; charset=utf-8", data: null, beforeSend: function () { HideNotFound(); },
            success: function (data) {
                $placearoundform.html(data);
                FinishSearchAround();
                if (data.length == 0) {
                    ShowNotFound();
                } else {
                    InitPoint(false);
                    Marker.Init(-1, $el);
                    SetPointn();
                }
            }, error: function (httpReq, status, exception) {
            }
        });
    });
    $endpoint.live('click', function () {
        HideSubList();
        /*SetPointb($(this).parent().parent().find('.address').text());*/
        Markerb.Init(1, $(this));
        SetPointb(Markerb.info);
    });
    $startpoint.live('click', function () {
        HideSubList();
        Markera.Init(0, $(this));
        SetPointa(Markera.info);
    });
    function viewPlace(el) {
        HideSubList();
        Marker.Init(-1, $(el));
        SetPointn();
        HideView('placepage', 'place-nav');
    }

    $resli.live('dblclick', function () {
        viewPlace(this);
    });

    $viewmap.live('click', function () {
        HideSubList();
        Marker.Init(-1, $(this));
        SetPointn();
    });
    function HideSubList() {
        $sublist.css('display', 'none');
    }
    $map.dblclick(function (e) {
        m_pzx = e.offsetX;
        m_pzy = e.offsetY;
        XenZ(true, m_pzx, m_pzy);
    });
    //$(document).bind('mousedown', function () { sliderOb.Clear(); });
    //.bind('contextmenu', function (e) { e.preventDefault(); })
    $(document).bind('keydown', function (e) {
        if (e.keyCode == 118) {
            sliderOb.Clear(); iDvs = (iDvs + 1 >= devices.length) ? 0 : iDvs + 1; $device.removeClass().addClass(devices[iDvs]); resizewindow(true);
            var el = $layout.find('.page.active');
            for (var i = 0; i < el.length; i++) {
                if ($(el[i]).attr('id') != 'mainpage') {
                    resizeElView($(el[i]).attr('id'));
                    break;
                }
            }
        }
    });
    $item0.click(function (e) {
        var x = parseInt(xcurR - curMapx);
        var y = parseInt(ycurR - curMapy - $header.height());

        $.ajax({ url: "/Home/GetExactCoordinate?zoom=" + curlevelz + "&x=" + x + "&y=" + y,
            type: 'POST', cache: false, dataType: 'Json',
            contentType: "text/html; charset=utf-8", data: null, beforeSend: function () { },
            success: function (data) {
                startLat = data[0];
                startLong = data[1];
                var pos = ConvertToMapP(startLat, startLong);
                Markera.UpdateCoor(startLat, startLong);
                Markera.UpdatePos(pos[0], pos[1]);
                SetPointa(data[2]);
            }, error: function () { }
        });
    });
    $item1.click(function (e) {
        var x = parseInt(xcurR - curMapx);
        var y = parseInt(ycurR - curMapy - $header.height());

        $.ajax({ url: "/Home/GetExactCoordinate?zoom=" + curlevelz + "&x=" + x + "&y=" + y,
            type: 'POST', cache: false, dataType: 'Json',
            contentType: "text/html; charset=utf-8", data: null, beforeSend: function () { },
            success: function (data) {
                endLat = data[0];
                endLong = data[1];
                var pos = ConvertToMapP(endLat, endLong);
                Markerb.UpdateCoor(endLat, endLong);
                Markerb.UpdatePos(pos[0], pos[1]);
                SetPointb(data[2]);
            }, error: function () { }
        });
    });
    $item2.click(function (e) {
        var x = parseInt(xcurR - curMapx);
        var y = parseInt(ycurR - curMapy - $header.height());

        $.ajax({ url: "/Home/GetExactCoordinate?zoom=" + curlevelz + "&x=" + x + "&y=" + y,
            type: 'POST', cache: false, dataType: 'Json',
            contentType: "text/html; charset=utf-8", data: null, beforeSend: function () { },
            success: function (data) {
                markLat = data[0];
                markLong = data[1];
                var pos = ConvertToMapP(markLat, markLong);
                Marker.UpdatePos(pos[0], pos[1]);
                Marker.UpdateCoor(markLat, markLong);
                SetPointn();
            }, error: function () { }
        });
    });
    $item3.click(function (e) {
        var x = parseInt(e.pageX - curMapx);
        var y = parseInt(e.pageY - $header.height() - curMapy);
        var type = parseInt($placetype.val());
        var range = parseInt($range.val());
        for (var i = 0; i < poinmark_arrs.length; i++) {
            if (poinmark_arrs[i].focus(x, y)) {
                x = poinmark_arrs[i].x;
                y = point_arrs[i].y
                Marker.UpdatePos(poinmark_arrs[i].x, point_arrs[i].y);
                Marker.UpdateCoor(poinmark_arrs[i].lat, poinmark_arrs[i].long);
                markLat = poinmark_arrs[i].lat;
                markLong = poinmark_arrs[i].long;
                break;
            }
        }
        $.ajax({ url: "/Home/GetPlaceAroundPoint?zoom=" + curlevelz + "&x=" + x + "&y=" + y + "&type=" + type + "&r=" + range,
            type: 'POST', cache: false, dataType: 'Json',
            contentType: "text/html; charset=utf-8", data: null, beforeSend: function () { HideNotFound(); },
            success: function (data) {
                $placearoundform.html(data[0]);
                FinishSearchAround();
                if (data.length == 0) {
                    ShowNotFound();
                } else {
                    InitPoint(false);
                    markLat = data[1];
                    markLong = data[2];
                    var pos = ConvertToMapP(markLat, markLong);
                    Marker.UpdatePos(pos[0], pos[1]);
                    Marker.UpdateCoor(markLat, markLong);
                    SetPointn();
                }
                //Marker.Init(-1, $el);
                //MoveMapToPosition(Marker.x, Marker.y, 10, true);
            }, error: function (httpReq, status, exception) {
            }
        });
    });
    function HideView(id, navid) {
        sliderOb.Clear();
        if (navDrag) { navDrag = false; return; }
        $('#' + id).find(slider).fadeOut('fast',function(){
            $('#' + id).animate({ left: -deviceW }, '0.1', 'linear', function () {
                $(this).removeClass('active').addClass('inactive');
                //$mainpage.removeClass('active').addClass('inactive');
            });
        });
        $('#' + navid).fadeOut('fast', function () {
            $(this).removeClass('show').addClass('hidden');
            $('#' + mainnav).fadeIn('fast', function () { $(this).removeClass('hidden').addClass('show'); });
        });
    }

    function resizeElView(id) {
        var heighttop = 27 + $('#' + id).find('.input_form').height();
        var heightcont = deviceH - heighttop - 42;
        $('#' + id).find('.m_bdcontent').height(heightcont);
        $('#' + id).find('.slider-content').height(heightcont).css('top', heighttop);
        var showslider = false;
        $('#' + id).removeClass('inactive').addClass('active')
        if ($('#' + id).find('.list_res').height() > heightcont) {
            var cSpanh = heightcont / $('#' + id).find('.list_res').css('margin-top', 0).height() * $('#' + id).find('.slider-content').height();
            $('#' + id).find('.slider-content span').css('top',0).height(cSpanh);
            var rate = cSpanh / heightcont;
            showslider = true;
            ResetSlider('#' + id, rate);
        }

        return showslider;
    }
    
    function ShowView(id, navid) {
        if (navDrag) { navDrag = false; return; }

        var el = $layout.find('.page.active');

        for (var i = 0; i < el.length; i++) {
            if ($(el[i]).attr('id') != 'mainpage') {
                $(el[i]).animate({ left: -deviceW }, '0.1', 'linear', function () { });
                break;
            }
        }

        var showslider = resizeElView(id);

        $('#' + id).css('left', deviceW - 10)
        .animate({ left: 0 }, '0.1', 'linear', function () {
            //$mainpage.removeClass('active').addClass('inactive');
            if (showslider) $(this).find(slider).fadeIn('fast');
        });

        $navs.find('.nav.show').fadeOut('fast', function () {
            $(this).removeClass('show').addClass('hidden');
            $('#' + navid).fadeIn('fast', function () { $(this).removeClass('hidden').addClass('show'); });
        });
    }
    $resli.live('click',function () {
        if ($(this).attr("class") != "focus") {
            $(this).parent().find('li.focus').removeClass('focus');
            $(this).addClass('focus');
        }
    });

    $yourlocation.click(function () {getLocation();});
    $butdir.click(function (e) {
        var idel = $(this).attr('id');
        if (idel == "movetop") {
            ChangeMapPosition(0, 200, 10, true);
        } else if (idel == "movebottom") {
            ChangeMapPosition(0, -200, 10, true);
        } else if (idel == "moveleft") {
            ChangeMapPosition(410, 0, 10, true);
        } else if (idel == "moveright") {
            ChangeMapPosition(-410, 0, 10, true);
        } else if (idel == "movecenter") {
            MoveMapToPosition(centerx, centery, 10, true);
        } else {
            getLocation();
        }
        e.preventDefault();
    });
    var Markera = new Marker("../Content/images/flag_a.png");
    var Markerb = new Marker("../Content/images/flag_b.png");
    var Marker = new Marker("../Content/images/flag.png");
    marker_arrs.push(Marker); marker_arrs.push(Markera); marker_arrs.push(Markerb);
    GetUri();
    DrawMap();
}